#include "matrix_zero.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void
setZeroes (int **matrix, int matrixSize, int *matrixColSize)
{
  int m = matrixSize;
  int n = *matrixColSize;
  int *row = (int *)malloc (m * sizeof (int));
  int *col = (int *)malloc (n * sizeof (int));
  memset (row, 0, m * sizeof (int));
  memset (col, 0, n * sizeof (int));

  // matrix[0][0] = 0;

  // 在下面实现将矩阵中为0的元素所在的行和列都置为0

  // record which row and col need to be set to 0
  for (int r = 0; r < m; ++r)
  {
    for (int c = 0; c < n; ++c)
    {
      if (matrix[r][c] == 0)
      {
        row[r] = 1;
        col[c] = 1;
      }
    }
  }

  // set target rows to 0
  for (int r = 0; r < m; ++r)
  {
    if (row[r] == 1)
    {
      for(int j = 0; j < n; ++j)
      {
        matrix[r][j] = 0;
      }
    } 
  }

  // set target cols to 0
  for (int c = 0; c < n; ++c)
  {
    if (col[c] == 1)
    {
      for(int i = 0; i < m; ++i)
      {
        matrix[i][c] = 0;
      }
    } 
  }

  free (row);
  free (col);
}

void
printMatrix (int **matrix, int matrixSize, int *matrixColSize)
{
  for (int i = 0; i < matrixSize; i++)
    {
      for (int j = 0; j < matrixColSize[i]; j++)
        {
          printf ("%d ", matrix[i][j]);
        }
      printf ("\n");
    }
}

void
freeMatrix (int **matrix, int matrixSize)
{
  for (int i = 0; i < matrixSize; i++)
    {
      free (matrix[i]);
    }
  free (matrix);
}
